package com.bbx.taxi.client.Bean.Message;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.provider.Settings.System;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.gclient.GMsgBroadcastReceiver;
import com.bbx.api.sdk.SDK;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Jmsg;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.util.LogUtils;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.Activity.login.LoginActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.DB.JmsgDB;
import com.bbx.taxi.client.DB.Util.DBHelper;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.PollingUtils;
import com.bbx.taxi.client.config.Config;

public class MyMesssage {
	public static MyMesssage mInstance;
	private String sn = "push_offline";// 序列号
	public static String sn_position = "push_position";// 获取地理位置的序列号
	private static List<String> sn_list = new ArrayList<String>();
    private int offline_num=10;
	public static MyMesssage getInstance() {
		mInstance = null;
		if (mInstance == null) {
			mInstance = new MyMesssage();
		}
		return mInstance;
	};

	public void onAllMessage(final Context context, final GMsg notify, final String uid,
			String token) {
		final Online mOnline = new Online();
		LogUtils.e("", "有消息");
		switch (notify.type) {
		// 在线消息
		case GMsg.NOTIFY_TYPE_ONLINE:
			mOnline.onOnline(context, (JSONObject) notify.data);
			break;
		// 消息类型是登陆，执行登陆操作
		case GMsg.NOTIFY_TYPE_LOGIN_STATUS_CHANGE:
			if (notify.stauts == 2) {
				LoginService.SDKlogin=true;
				LogUtils.e("bbx", "SDK登陆成功");
				 MyApplication mApplication=MyApplication.getInstance();
				 if(mApplication!=null){
	        	   mApplication.onStartLocation();
				 }
				// 获取离线
				getOfflineMessage(uid, context);
			} else {
				LoginService.SDKlogin=false;
				LogUtils.e("bbx", "SDK登陆失败");
				context.stopService(new Intent(context, LoginService.class));
				// SDK登陆
				SDK.ins.login(uid, token);
			}
			break;
		}
		// 获取离线消息
		try {
			JSONObject j = (JSONObject) notify.data;
			if (sn_list.contains(j.getString("sn"))) {
				LogUtils.e("offline", "离线消息：" + notify.data);
				final JSONObject jsmg_json = j.getJSONObject(GMsg.msg_jmsg);
				final JSONArray msgs = jsmg_json.getJSONArray(GMsg.msg_msgs);
				// Jmsg jmsg = (Jmsg) new JsonBuild().getData(Jmsg.class,
				// jsmg_json.toString());
				if (msgs != null) {// 有离线消息，存储数据库
					// 存储数据库
					final JmsgDB db_jmsg = new JmsgDB(context);
					new AsyncTask<Void, Void, Void>() {

						@Override
						protected Void doInBackground(Void... arg0) {
							try{
							for (int i = 0; i < msgs.length(); i++) {
								JSONObject jo = new JSONObject(msgs.get(i).toString());
								Msgs.Data msgs_data = null;
								JSONObject jmsg_data = null;
								jmsg_data = new JSONObject(jo.getString(GMsg.msg_data));
								msgs_data = (Msgs.Data) new JsonBuild().getData(
										Msgs.Data.class, jmsg_data.toString());
								// 存储消息
								String order_id = msgs_data.getOrder_id();
								String time = DateFormat.getTime(Long.parseLong(jo
										.getString(GMsg.msg_time)));
								int type = jo.getInt(GMsg.msg_type);
								db_jmsg.onWrite(order_id, time, type, jo.toString());
		                       try{
		                    		// 处理订单数据库,
		   						mOnline.onProcessingMessage(context, type, jmsg_data.toString(),
		   								false, (JSONObject) notify.data);
		                       }catch(Exception e){
		                    	   //订单数据出现问题,跳过本次循环
		                    	   continue;
		                       }
							
							}
							
						}catch(Exception e){
						}		
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
                           try{
							JSONObject jo = new JSONObject(msgs.get(msgs.length() - 1)
									.toString());
							String start_id = jo.getString("id");
							int yeshu=Integer.parseInt(start_id)/offline_num;
							int next=(yeshu+1)*offline_num;
							SharedPreUtil.putStringValue(context,
									SharedPreEncryptUtil.start_id,
									String.valueOf(next));
							String maxid = jsmg_json.getString("maxid");
							// 判断maxid是否等于数组里面最后一个消息的Id,maxid比较大的话还有离线消息，则在请求一次
							if (Long.parseLong(maxid) >= Long.parseLong(start_id)) {
								getOfflineMessage(uid, context);
							} else {
								SharedPreUtil.putStringValue(context,
										SharedPreEncryptUtil.start_id,
										String.valueOf(0));
								// 离线消息获取完成
								LogUtils.e("offline", "离线消息完成");
								mOnline.sendBroadcast(context, GMsg.OFFLINE, null,null);
							}}catch(Exception e){}
							super.onPostExecute(result);
						}
						
					}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

				}
			}
		} catch (JSONException e) {
			try{
			//报错，代表msgs解析失败，就是离线消息没有
			LogUtils.e("offline", "离线消息完成");
			mOnline.sendBroadcast(context, GMsg.OFFLINE, null,null);
			JSONObject j = (JSONObject) notify.data;
			JSONObject jsmg_json = j.getJSONObject(GMsg.msg_jmsg);
//			String maxid = jsmg_json.getString("maxid");
				SharedPreUtil.putStringValue(context,
					SharedPreEncryptUtil.start_id,
					String.valueOf(0));
			}catch(Exception e1){}
		}
		// 获取地理位置
		try {
			JSONObject j = (JSONObject) notify.data;
			if (j.getString("sn").startsWith(sn_position)) {
				mOnline.sendBroadcast(context, GMsg.ONLINE_POSITION,
						j.toString(),null);
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 获取离线消息
	 */
	public void getOfflineMessage(String uid, Context context) {
		String start_id = SharedPreUtil.getStringValue(context,
				SharedPreEncryptUtil.start_id, "0");
		LogUtils.e("offline", Integer.parseInt(start_id)+"");
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject();
			jsonObject.put("cmd", 3);
			jsonObject.put("uid", uid);
			jsonObject.put("start_id", Integer.parseInt(start_id));
			jsonObject.put("count", offline_num);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		String sn_string = sn + "_" + (new Date().getTime());
		sn_list.add(sn_string);
		// 请求离线消息
		SDK.ins.mClient.request(uid, sn_string, 10, jsonObject.toString());
	}
}
